package cn.jiyun.controller;

import cn.jiyun.pojo.User;
import cn.jiyun.service.UserService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.List;

@Controller
@RequestMapping("user")
public class UserController {
    @Autowired
    private UserService userService;

    @GetMapping("findAll")
    public String findAll(Model model, @RequestParam(required = true, defaultValue = "1") Integer pageNum) {
        PageHelper.startPage(pageNum, 2);
        List<User> list = userService.findAll();
        PageInfo<User> page = new PageInfo<>(list);
        model.addAttribute("list", page);
        return "ulist";
    }

    @GetMapping("del")
    public String del(Integer id) {
        userService.del(id);
        return "redirect:findAll";
    }

    @GetMapping("tzadd")
    public String tzadd() {
        return "add";
    }


    @GetMapping("hx")
    public String hx(Integer id, Model model) {
        User user = userService.hx(id);
        model.addAttribute("user", user);
        return "update";
    }

    @PostMapping("addOrupdate")
    public String addOrupdate(User user) {
        if (user.getId() == null) {
            userService.add(user);
        } else {
            userService.update(user);
        }

        return "redirect:findAll";
    }

}
